package com.github.caijinglong

import com.alibaba.fastjson.JSON
import com.github.caijinglong.bean.Card
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import java.io.FileOutputStream

val handler = Handler()



fun main(args: Array<String>) {
    val src = zsSrc

    val decodeText = handler.getDecodeText(src)
    val jsonObject = JSONObject(decodeText)
    println(jsonObject)

//    handler.showAllProp(jsonObject)
    modifyCard(jsonObject) { card ->
        card.upgrades = 1
        !Handler.DEBUFF_CARD.contains(card.id)
    }
    maxHealth(jsonObject)

    println(jsonObject.toString())


    val filePath = "testTarget.txt"
    FileOutputStream(filePath).bufferedWriter().apply {
        val encodeStr = handler.encode(jsonObject.toString())
        write(encodeStr)
        flush()
    }

    File(filePath).copyTo(File(src), true)
}

fun maxHealth(data: JSONObject) {
    val max = data.getInt("max_health")
    data.put("current_health", max)
}

fun modifyCard(jsonObject: JSONObject, cardHandler: (card: Card) -> Boolean) {
    val key = "cards"
    val cards = jsonObject.getJSONArray(key)
    val new = JSONArray()
    cards.forEach {
        val card = JSON.parseObject(it.toString(), Card::class.java)
        val save = cardHandler(card)
        if (save) {
            new.put(card.toJsonObject())
        }
    }
    jsonObject.put(key, new)
}